package code

import (
	"errors"
	"fmt"
	"github.com/farmerx/gorsa"
	"log"
)

var Pubkey = `-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKhtIvkFhhgbGymSx3p5eKlnOjHjxjCQ
E/pQB2pr2iaLQHPmuzeDWrdFRm4FLK6KS89umeeyROllFDjt9Hdu6SMCAwEAAQ==
-----END PUBLIC KEY-----
`

var Pirvatekey = `-----BEGIN PRIVATE KEY-----
MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEAqG0i+QWGGBsbKZLH
enl4qWc6MePGMJAT+lAHamvaJotAc+a7N4Nat0VGbgUsropLz26Z57JE6WUUOO30
d27pIwIDAQABAkBDGef7CkZYSERUFdQ/aTG3XBcFVVfadSxgZ43syjdJbz9HvXwC
ffqnn0K8EwCJqWe3+VDonzCqtSEsICWhddrhAiEA3wPOFPqWZ/LYZtYtRup/yADP
w7D64CeESYftiPv3pWsCIQDBVmaKRnm2aePH7mHI0N27syhAGtS3bmw3I23Il2AB
KQIhAKW0FxDBbLYJ2771TqkNnipGaBl4S7/3vLRB+j25MjXHAiEAoODKdqlqQjYe
ypE8YSQcPkI4bg9ljjWeastaYR5FTvECIQC0fJWGno9sx/mgrI+LnucdSy3HVRjj
xZtqsqme3vDbjg==
-----END PRIVATE KEY-----

`

// 初始化设置公钥和私钥
//
//	func init() {
//		if err := gorsa.RSA.SetPublicKey(Pubkey); err != nil {
//			log.Fatalln(`set public key :`, err)
//		}
//		if err := gorsa.RSA.SetPrivateKey(Pirvatekey); err != nil {
//			log.Fatalln(`set private key :`, err)
//		}
//	}
func SetPublicKeyAndPrivateKey(Pubkey string, Pirvatekey string) {
	if err := gorsa.RSA.SetPublicKey(Pubkey); err != nil {
		log.Fatalln(`set public key :`, err)
	}
	if err := gorsa.RSA.SetPrivateKey(Pirvatekey); err != nil {
		log.Fatalln(`set private key :`, err)
	}
}

// 公钥加密私钥解密
func ApplyPubEPriD(str string) error {
	pubenctypt, err := gorsa.RSA.PubKeyENCTYPT([]byte(str))
	if err != nil {
		fmt.Println("加密失败")
		return errors.New(`加密失败`)
	}

	pridecrypt, err := gorsa.RSA.PriKeyDECRYPT(pubenctypt)
	if err != nil {
		return errors.New(`解密失败`)
	}
	if string(pridecrypt) != `hello world` {
		return errors.New(`解密失败`)
	} else {
		fmt.Println("解密成功", string(pridecrypt))
	}
	return nil
}

// 公钥解密私钥加密
func ApplyPriEPubD() error {
	prienctypt, err := gorsa.RSA.PriKeyENCTYPT([]byte(`hello world`))
	if err != nil {
		return err
	}

	pubdecrypt, err := gorsa.RSA.PubKeyDECRYPT(prienctypt)
	if err != nil {
		return err
	}
	if string(pubdecrypt) != `hello world` {
		return errors.New(`解密失败`)
	}
	return nil
}
